import axios from "axios"
import store from "@/store"
import { Message } from "element-ui"
import router from "@/router"

const service = axios.create({
    // baseURL: process.env.VUE_APP_BASE_API, //基础地址
    baseURL: "/api", //基础地址
    timeout: 10000,
})

service.interceptors.request.use((config) => {
    //注入token
    if (store.getters.token) {
        config.headers['token'] = `${store.getters.token}`
    }
    return config
}, (error) => {
    //失败执行promise
    return Promise.reject(error)
})

//响应拦截器
service.interceptors.response.use((response) => {
    const { data, message, success } = response.data
    if (success) {
        return data
    } else {
        Message({ type: "error", message: message })
        return Promise.reject(new Error(message))
    }
}, async(error) => {
    // if (error.response.status === 401) {
    //     await store.dispatch("user/logout")
    //     router.push('/login')
    // }
    Message({ type: "error", message: error.message })
    return Promise.reject(error)
})

export default service